package com.fresh.bus.chat.business;

import java.util.Map;

import javax.annotation.Resource;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import com.fresh.bus.canoe.message.Response;
import com.fresh.bus.canoe.server.support.DefaultLifecycleHandler;
import com.fresh.bus.canoe.session.Session;
import com.fresh.bus.chat.ctrl.OpCodes;

public class BusLineListener implements MessageListener {
	private static final Logger log = LoggerFactory
			.getLogger(BusLineListener.class);
	public UserService userService;	
	public ExperienceService expService;

	private Session session;
	private DefaultLifecycleHandler handler;
	private Map<String, Object> msgData;
	
	private RedisSerializer<?> serializer = new StringRedisSerializer();
	private RedisSerializer<String> stringSerializer = new StringRedisSerializer();
	private ObjectMapper mapper = new ObjectMapper();
	

	public enum Command {
		SYN_TIME, START_TALK, END_TALK, SYN_FEMALE_NUM, SYN_MALE_NUM
	}

	public BusLineListener(Session session, DefaultLifecycleHandler handler) {
		super();
		this.session = session;
		this.handler = handler;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onMessage(Message message, byte[] pattern) {
		String convertedMessage = (String) serializer.deserialize(message
				.getBody());
		// String convertedChannel = stringSerializer.deserialize(pattern);

		try {
			msgData = mapper.readValue(convertedMessage, Map.class);
			String command = (String) msgData.get("command");
			log.debug("Current command is " + command);
			Command cd = Command.valueOf(command.toUpperCase());
			switch (cd) {
			case START_TALK:
				startTalk();
				break;
			case END_TALK:
				endTalk();
				break;
			}
		} catch (Exception e) {
			log.error("", e);
		}
	}

	private void endTalk() {
		if(this.session.getAttribute("isTalking") != null){
			this.session.removeAttribute("to");
			this.session.removeAttribute("isTalking");
			
			expService.update(session, null,OpCodes.END_TALK);
			
			Response response = new Response(OpCodes.END_TALK);
			response.setData("");
			handler.sendResponse(response, session);
		}
	}

	private void startTalk() {
		Response response = new Response(OpCodes.START_TALK);
		String id = (String) session.getAttribute("to");
		response.setData(userService.findUser(id));
		handler.sendResponse(response, session);
	}
}
